<template>
  <div class="pagination">
    <button @click="page-=1" :disabled="page===1">上一页</button>
    <button
        v-show="startEnd.start>page"
        @click="page=1"
        :class="page === 1 ? 'active' : ''"
    >1
    </button>


    <button v-show="startEnd.start>2">···</button>

    <button
        v-for="item in pageContainer"
        :key="item"
        @click="page = item"
        :class="page === item ? 'active' : ''"
    >{{ item }}
    </button>

    <button v-show="startEnd.end < totalPages - 1">···</button>


    <button
        v-show="startEnd.end < totalPages"
        @click="page = totalPages"
        :class="page === totalPages ? 'active' : ''"
    >
      {{ totalPages }}
    </button>
    <button @click="page+=1" :disabled="page===totalPages">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  data() {
    return {
      page: this.pageNo
    }
  },
  props: ['pageNo', 'totalPages', 'total', 'continuousPage'],
  computed: {
    startEnd() {
      let start = 1; // 初始的连续页头页
      let end = 1; // 初始的连续页尾页
      // 计算获得连续页的开头和结尾
      if (this.totalPages < this.continuousPage) {
        // 当连续页的数量小于总数量
        start = 1;
        end = this.totalPages;
      } else {
        // 当连续页的数量大于总数量
        // 计算获得 连续页开头和结尾 (加入当前页 3 连续页 3 所以 2 3 4)
        start = this.page - Math.floor(this.continuousPage / 2);
        end = this.page + Math.floor(this.continuousPage / 2);

        // 特殊情况 连续页 3 当前页 1
        // 因为start可能小于1,让start等于1 end等于连续页
        if (start < 1) {
          start = 1;
          end = this.continuousPage;
        }
        // 特殊情况 连续页 3 总页数5 当前页 5
        // 因为end的值可能大于totalPages,让end变成总页数,计算start
        if (end > this.totalPages) {
          end = this.totalPages;
          start = this.totalPages - this.continuousPage + 1;
        }
      }
      return {
        start,
        end
      }
    },
    pageContainer() {
      const {start, end} = this.startEnd;
      const arr = [];
      for (let i = start; i <= end; i++) {
        arr.push(i);
      }
      return arr;
    }
  },
  watch: {
    page() {
      this.$emit('toPageList', this.page)
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>